<template>
  <a-drawer
    :title="title"
    :width="drawerWidth"
    @close="handleCancel"
    :visible="visible"
    :confirmLoading="confirmLoading"
    style="height: 100%; overflow: auto; padding-bottom: 53px"
  >
    <a-spin :spinning="confirmLoading">
      <a-form-model ref="form" :model="model" :rules="validatorRules" labelAlign="left">
        <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" prop="signInName" label="打卡模板名称">
          <a-input placeholder="请输入打卡模板名称" v-model="model.signInName" :max-length="20" />
        </a-form-model-item>
      </a-form-model>

      <a-card style="margin-top: 24px" :bordered="false" title="打卡计划">
        <div class="ant-table ant-table-large ant-table-scroll-position-left ant-table-scroll-position-right">
          <div class="ant-table-content">
            <div class="ant-table-scroll">
              <!---->
              <div class="ant-table-body">
                <table class="">
                  <thead class="ant-table-thead">
                    <tr>
                      <th key="signInItem" class="">
                        <span class="ant-table-header-column">
                          <div>
                            <span class="ant-table-column-title">打卡项目</span
                            ><span class="ant-table-column-sorter"></span>
                          </div>
                        </span>
                      </th>
                      <th class="" v-for="day in weekItems" :key="day.id">
                        <span class="ant-table-header-column">
                          <div>
                            <span class="ant-table-column-title">
                              {{ day.title }}
                            </span>
                            <a-icon type="close" @click="cancelDay(day.id, day.title)" />
                            <span class="ant-table-column-sorter"></span>
                          </div>
                        </span>
                      </th>
                    </tr>
                  </thead>
                  <tbody class="ant-table-tbody">
                    <tr class="ant-table-row ant-table-row-level-0" v-for="(item, index) in clockInItems" :key="index">
                      <td class="" style="width: 13%;">{{ item.title }}</td>
                      <td
                        class=""
                        v-for="(day, dindex) in weekItems"
                        :key="dindex"
                        @click.stop="modifyTime(item.title, day.id)"
                      >
                        <span style="cursor: pointer">{{ formatValue(item.title, day.id) }}</span>
                        <a-icon
                          v-if="formatValue(item.title, day.id) != ''"
                          type="close"
                          @click.stop="cancelTime(day.title, item.title, day.id)"
                        />
                      </td>
                      <!-- <td class="">{{ formatValue(item.title, 'signInJsonMonday') }} <a-icon v-if="formatValue(item.title, 'signInJsonMonday') != ''" type="close" @click="cancelTime('星期一', item.title, 'signInJsonMonday')" /></td>
                      <td class="">{{ formatValue(item.title, 'signInJsonTuesday') }} <a-icon v-if="formatValue(item.title, 'signInJsonTuesday') != ''" type="close" @click="cancelTime('星期二', item.title, 'signInJsonTuesday')" /></td>
                      <td class="">{{ formatValue(item.title, 'signInJsonWednesday') }} <a-icon v-if="formatValue(item.title, 'signInJsonWednesday') != ''" type="close" @click="cancelTime('星期三', item.title, 'signInJsonWednesday')" /></td>
                      <td class="">{{ formatValue(item.title, 'signInJsonThursday') }} <a-icon v-if="formatValue(item.title, 'signInJsonThursday') != ''" type="close" @click="cancelTime('星期四', item.title, 'signInJsonThursday')" /></td>
                      <td class="">{{ formatValue(item.title, 'signInJsonFriday') }} <a-icon v-if="formatValue(item.title, 'signInJsonFriday') != ''" type="close" @click="cancelTime('星期五', item.title, 'signInJsonFriday')" /></td>
                      <td class="">{{ formatValue(item.title, 'signInJsonSaturday') }} <a-icon v-if="formatValue(item.title, 'signInJsonSaturday') != ''" type="close" @click="cancelTime('星期六', item.title, 'signInJsonSaturday')" /></td>
                      <td class="">{{ formatValue(item.title, 'signInJsonSunday') }} <a-icon v-if="formatValue(item.title, 'signInJsonSunday') != ''" type="close" @click="cancelTime('星期日', item.title, 'signInJsonSunday')" /></td> -->
                    </tr>
                    <!-- <tr class="ant-table-row ant-table-row-level-0" data-row-key="1">
                      <td class="">测试打卡模板1</td>
                      <td class="">2022-01-11 14:12:35</td>
                      <td class="">张启壬</td>
                      <td
                        class="ant-table-fixed-columns-in-body ant-table-row-cell-break-word"
                        style="text-align: center"
                      >
                        <span data-v-3818d670=""
                          ><a data-v-3818d670="">编辑</a>
                          <div data-v-3818d670="" role="separator" class="ant-divider ant-divider-vertical"></div>
                          <a data-v-3818d670="" class="">删除</a></span
                        >
                      </td>
                    </tr> -->
                  </tbody>
                </table>
              </div>
            </div>
          </div>
        </div>
      </a-card>
    </a-spin>

    <div class="drawer-bootom-button">
      <a-popconfirm title="确定放弃编辑？" @confirm="handleCancel" okText="确定" cancelText="取消">
        <a-button style="margin-right: 0.8rem">取消</a-button>
      </a-popconfirm>
      <a-button @click="handleOkConfirm" type="primary" :loading="confirmLoading">提交</a-button>
    </div>

    <modify-time-modal ref="modifyTime" @modifyTime="handleModifyTime" />
  </a-drawer>
</template>

<script>
import { postAction, getAction } from '@/api/manage'
import ModifyTimeModal from './ModifyTimeModal'
import moment from 'moment'
import { mapGetters } from 'vuex'
export default {
  name: 'ClockInTemplateModal',
  components: {
    ModifyTimeModal
  },
  data() {
    return {
      weekItems: [
        {
          id: 'signInJsonMonday',
          title: '星期一'
        },
        {
          id: 'signInJsonTuesday',
          title: '星期二'
        },
        {
          id: 'signInJsonWednesday',
          title: '星期三'
        },
        {
          id: 'signInJsonThursday',
          title: '星期四'
        },
        {
          id: 'signInJsonFriday',
          title: '星期五'
        },
        {
          id: 'signInJsonSaturday',
          title: '星期六'
        },
        {
          id: 'signInJsonSunday',
          title: '星期日'
        }
      ],
      clockInItems: [
        {
          id: '1+1',
          title: '空腹血糖'
        },
        {
          id: '1+2',
          title: '早餐后血糖'
        },
        {
          id: '1+3',
          title: '午餐前血糖'
        },
        {
          id: '1+4',
          title: '午餐后血糖'
        },
        {
          id: '1+5',
          title: '晚餐前血糖'
        },
        {
          id: '1+6',
          title: '晚餐后血糖'
        },
        {
          id: '1+7',
          title: '睡前血糖'
        },
        {
          id: '1+8',
          title: '凌晨血糖'
        },
        {
          id: '5+1',
          title: '早餐饮食'
        },
        {
          id: '5+2',
          title: '午餐饮食'
        },
        {
          id: '5+3',
          title: '晚餐饮食'
        },
        {
          id: '3+0',
          title: '运动'
        },
        {
          id: '4+1',
          title: '早用药'
        },
        {
          id: '4+2',
          title: '午用药'
        },
        {
          id: '4+3',
          title: '晚用药'
        },
        {
          id: '4+4',
          title: '睡前用药'
        },
        {
          id: '9+1',
          title: '早胰岛素'
        },
        {
          id: '9+2',
          title: '午胰岛素'
        },
        {
          id: '9+3',
          title: '晚胰岛素'
        },
        {
          id: '9+4',
          title: '睡前胰岛素'
        },
        {
          id: '10+0',
          title: '睡眠'
        },
        {
          id: '11+1',
          title: '早营养素'
        },
        {
          id: '11+2',
          title: '午营养素'
        },
        {
          id: '11+3',
          title: '晚营养素'
        },
        {
          id: '11+4',
          title: '睡前营养素'
        },
        {
          id: '2+1',
          title: '早血压'
        },
        {
          id: '2+2',
          title: '晚血压'
        },
        {
          id: '8+0',
          title: '尿酮'
        },
        {
          id: '6+0',
          title: '体重'
        },
        {
          id: '7+0',
          title: '腰围'
        }
      ],
      drawerWidth: 700,
      title: '操作',
      visible: false,
      model: {},
      notify: false,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 2 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 8 }
      },
      confirmLoading: false
    }
  },
  computed: {
    validatorRules: function() {
      return {
        signInName: [{ required: true, message: '请输入打卡模板名称!' }]
      }
    }
  },
  created() {},
  methods: {
    ...mapGetters(['doctorId', 'orgCode']),
    detail() {
      getAction('signin/template/get', { id: this.model.dataId || 0, orgCode: this.orgCode() }).then(res => {
        if (res.success) {
          this.weekItems.forEach(v => {
            if (
              !res.result[v.id].some(n => {
                if (n.item == '凌晨血糖') {
                  return true
                }
              })
            ) {
              res.result[v.id].push({
                endtime: '07:00',
                item: '凌晨血糖',
                item_id: '1+8',
                recordType: 1,
                starttime: '06:00',
                subType: 8
              })
            }
            if (
              !res.result[v.id].some(n => {
                if (n.item == '睡眠') {
                  return true
                }
              })
            ) {
              res.result[v.id].push({
                endtime: '10:00',
                item: '睡眠',
                item_id: '10+0',
                recordType: 10,
                starttime: '06:00',
                subType: 0
              })
            }
          })
          this.model = res.result
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    add() {
      //初始化默认值
      this.edit({ dataId: null })
    },
    edit(record) {
      this.resetScreenSize() // 调用此方法,根据屏幕宽度自适应调整抽屉的宽度
      this.model = Object.assign({}, record)

      //根据菜单类型，动态展示页面字段
      console.log('record: ', record)
      this.visible = true
      this.detail()
    },
    close() {
      this.$emit('close')
      this.disableSubmit = false
      this.visible = false
      this.$refs.form.resetFields()
    },
    formatValue(title, day) {
      if (this.model && this.model[day]) {
        let obj = this.model[day].find(function(value) {
          return value.item == title
        })

        if (obj?.starttime) {
          return obj?.starttime + ' - ' + obj?.endtime
        } else {
          return ''
        }
      } else {
        return ''
      }
    },
    cancelDay(day, title) {
      let that = this
      this.$confirm({
        title: '是否删除' + title + '的打卡时间?',
        onOk() {
          that.model[day].forEach((item, index) => {
            that.model[day][index].starttime = ''
            that.model[day][index].endtime = ''
            that.$set(that.model[day], index, that.model[day][index])
          })
        },
        onCancel() {
          console.log('Cancel')
        },
        class: 'test'
      })
    },
    modifyTime(title, day) {
      const formatedValue = this.formatValue(title, day)
      if (formatedValue) {
        const obj = this.model[day].find(function(value) {
          return value.item == title
        })
        this.$refs.modifyTime.edit({ title, day }, JSON.parse(JSON.stringify(obj)))
        this.$refs.modifyTime.title = '修改时间'
      } else {
        this.$refs.modifyTime.edit({ title, day }, {})
        // this.$refs.modifyTime.visible = true
        this.$refs.modifyTime.title = '添加时间'
      }
    },
    cancelTime(week, title, day) {
      let that = this
      this.$confirm({
        title: '是否删除' + week + title + '打卡事件?',
        content: h => (
          <a-checkbox checked={that.notify} onChange={this.onChange}>
            同步每天此时间段
          </a-checkbox>
        ),
        onOk() {
          if (that.notify == true) {
            that.weekItems.forEach(item => {
              const index = that.model[item.id].findIndex(function(value) {
                return value.item == title
              })
              that.model[item.id][index].starttime = ''
              that.model[item.id][index].endtime = ''
              that.$set(that.model[item.id], index, that.model[item.id][index])
            })
          } else {
            const index = that.model[day].findIndex(function(value) {
              return value.item == title
            })
            that.model[day][index].starttime = ''
            that.model[day][index].endtime = ''
            that.$set(that.model[day], index, that.model[day][index])
          }
          that.notify = false
        },
        onCancel() {
          that.notify = false
          console.log('Cancel')
        },
        class: 'test'
      })
    },
    handleOkConfirm() {
      const that = this
      this.$confirm({
        title: '修改打卡计划',
        content: h => <div style="color:red;">修改后关联此模板的患者打卡计划将同步变更，是否确定修改？</div>,
        onOk() {
          that.handleOk()
        },
        onCancel() {
          console.log('Cancel')
        },
        class: 'test'
      })
    },
    handleOk() {
      const that = this
      // 触发表单验证
      this.$refs.form.validate(valid => {
        if (valid) {
          const empty = this.weekItems.some(v => {
            return this.model[v.id].some(n => {
              if (n.starttime) {
                return true
              }
            })
          })
          if (!empty) {
            this.$message.warning('至少设置一项！')
            return
          }
          that.confirmLoading = true

          let model = JSON.parse(JSON.stringify(this.model))
          model.dataId = model.dataId == 0 ? null : model.dataId
          model = Object.assign(model, { doctorId: this.doctorId(), orgCode: this.orgCode() })
          console.log('req model', model)

          postAction('signin/template/edit', model)
            .then(res => {
              if (res.success) {
                that.$message.success(res.message)
                that.$emit('ok')
              } else {
                that.$message.warning(res.message)
              }
            })
            .finally(() => {
              that.confirmLoading = false
              that.close()
            })
        } else {
          return false
        }
      })
    },
    handleCancel() {
      this.close()
    },
    onChange(e) {
      this.notify = e.target.checked
    },
    handleModifyTime(data) {
      console.log(data)
      let that = this
      if (data.notify == false) {
        const index = that.model[data.info.day].findIndex(function(value) {
          return value.item == data.info.title
        })
        that.model[data.info.day][index].starttime = data.data.starttime.format('HH:mm')
        that.model[data.info.day][index].endtime = data.data.endtime.format('HH:mm')
        that.$set(that.model[data.info.day], index, that.model[data.info.day][index])
      } else {
        that.weekItems.forEach(item => {
          const index = that.model[item.id].findIndex(function(value) {
            return value.item == data.info.title
          })
          that.model[item.id][index].starttime = data.data.starttime.format('HH:mm')
          that.model[item.id][index].endtime = data.data.endtime.format('HH:mm')
          that.$set(that.model[item.id], index, that.model[item.id][index])
        })
      }
    },
    // 根据屏幕变化,设置抽屉尺寸
    resetScreenSize() {
      let screenWidth = document.body.clientWidth
      if (screenWidth < 500) {
        this.drawerWidth = screenWidth
      } else {
        this.drawerWidth = document.body.clientWidth - 210
      }
    }
  }
}
</script>

<style scoped>
/* .ant-table-thead>tr:first-child>th:first-child {
  width: 150px;
} */
.avatar-uploader > .ant-upload {
  width: 104px;
  height: 104px;
}
.ant-upload-select-picture-card i {
  font-size: 49px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}

.ant-table-tbody .ant-table-row td {
  padding-top: 10px;
  padding-bottom: 10px;
}

.drawer-bootom-button {
  position: absolute;
  bottom: -8px;
  width: 100%;
  border-top: 1px solid #e8e8e8;
  padding: 10px 16px;
  text-align: right;
  left: 0;
  background: #fff;
  border-radius: 0 0 2px 2px;
}
</style>

